package com.xiaomaoguai.fcp.utils;

import com.xiaomaoguai.fcp.kepler.utils.Base64Utils;
import com.xiaomaoguai.fcp.kepler.utils.RSAUtils;
import lombok.extern.log4j.Log4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;


/**
 * 
 * 类FileUtils.java的实现描述：文件处理工具类
 * 
 * @author zengjuncai 2017年10月26日 下午2:26:51
 */
@Log4j
public class FileUtils2 {

	/**
	 * 创建文件工具类.
	 *
	 * @param saveFile the save file
	 * @return the file
	 */
	public static File createFile(String saveFile) {
		File file = new File(saveFile);
		return file;
	}

	/**
	 * 创建一个文件流.
	 *
	 * @param fileName the file name
	 * @return the file input stream
	 * @throws java.io.FileNotFoundException the file not found exception
	 */
	public static FileInputStream createFileInputStream(String fileName) throws FileNotFoundException {
		FileInputStream inputStream = new FileInputStream(fileName);
		return inputStream;

	}

	/**
	 * 从文件路径拿到最后的文件名.
	 *
	 * @param filePath the file path
	 * @return the last file name
	 */
	public static String getLastFileName(String filePath) {
		String[] tmpname = filePath.split("/");
		if (tmpname.length > 0) {
			return tmpname[tmpname.length - 1];
		} else {
			return filePath;
		}
	}

	/**
	 * 计算md5.
	 *
	 */
	// public static String getMd5Hex(InputStream data) throws IOException{
	// String md5hex=DigestUtils.md5Hex(data);
	// return md5hex;
	// }

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	/**
	 * Takes the raw bytes from the digest and formats them correct.
	 * 
	 * @param bytes
	 *            the raw bytes from the digest.
	 * @return the formatted bytes.
	 */
	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}

	/**
	 * Encode SHA 1.
	 *
	 * @param str the str
	 * @return the string
	 */
	public static String encodeSHA1(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	

	/**
	 * @Title: encryptFile
	 * @Description: 加密文件
	 * @param publicKey
	 * @param sourceFilepath
	 * @param localFilePath
	 * 设定文件 @return void 返回类型 @throws
	 */
	public static void encryptFile(String publicKey, String sourceFilepath, String localFilePath) {
		FileOutputStream fos = null;
		try {
			byte[] data = Base64Utils.fileToByte(sourceFilepath);
			byte[] resData = RSAUtils.encryptByPublicKey(data, publicKey);
			fos = new FileOutputStream(new File(localFilePath));
			fos.write(resData);
		} catch (Exception e) {
			log.error("文件加密失败,zaFilePath:" + sourceFilepath, e);
			throw new RuntimeException("文件加密失败");
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					log.error("输入文件流关闭失败",e);
				}
			}
		}
	}

	/**
	 * @Title: decryptFileFromPartner 
	 * @Description: 解密合作方的文件 
	 * @param  privateKey
	 * @param  sourceFilePath
	 * @param  localFilePath
	 * 设定文件 @return void 返回类型 @throws
	 */
	public static void decryptFile(String privateKey, String sourceFilePath, String localFilePath) {
		FileOutputStream fos = null;
		try {
			byte[] data = Base64Utils.fileToByte(sourceFilePath);
			byte[] resData = RSAUtils.decryptByPrivateKey(data, privateKey);
			fos = new FileOutputStream(new File(localFilePath));
			fos.write(resData);
		} catch (Exception e) {
			log.error("文件解密失败,filePath:" + sourceFilePath, e);
			throw new RuntimeException("文件解密失败");
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					log.error("输入文件流关闭失败",e);
				}
			}
		}
	}
	 
}
